<script setup lang="ts" name="sign-agreen">
import router from '@/router'
import { SearchForm } from '@fl/components'
import { agreement } from '@fl/api/purchase'
import FlUploadProgress from '@fl/components/fl-upload-progress.vue'
import { FlagStatusEnum, SignStatusEnum, agreementStatusEnum, auditStatusEnum } from '../constant'
import { createMapEnum } from '../mapEnum'
import { useForm, useRejectForm } from './hooks/use-form'
import type { IProps } from './types'
import { isAdmin, isPurchaser, isSupplier } from '../hooks/use-role'
import { cloneDeep } from 'lodash-es'
import { useGetAuthUrl } from '@fl/api/supplier'

const { useAagreementMetaAudit, useAddAgreementMetaInfo, useEditAgreementMetaInfo, useSignAgreement } = agreement(isAdmin.value)
const agreementEnum = createMapEnum(agreementStatusEnum)
const { group, form, onSign, uploadKey, showAddSubmit, rules, formInstanceRef, instanceRef, refetchAgreen, queryId } = useForm()

const { form: rejectForm, rules: rejectRules, visible: rejectVisible, schema: rejectSchema, instanceRejectRef: rejectFormRef, openDialog: openRejectDialog, closeDialog: closeRejectDialog } = useRejectForm()
const uploadRejectFile = ref(null)

const route = useRoute()

const { path, fullPath } = route

const index = path.lastIndexOf('sign-agreen')
const signPath = `${path.slice(0, index)}agreement`

const { mutate: addAgreen, isPending: isPendingAdd } = useAddAgreementMetaInfo()
const { mutate: editAgreen, isPending: isPendingEdit } = useEditAgreementMetaInfo()
const { mutate: signAgreement, isPending: isPendingSign } = useSignAgreement()
const { mutate: auditAgreement, isPending: isPendingAudit } = useAagreementMetaAudit()

const authUrlParams = computed(() => ({
    redirectUrl: location.href,
    flag: !isAdmin.value,
}))

const { data: authUrlData } = useGetAuthUrl(authUrlParams)
// watchEffect(() => {
//     queryId.value = route.query.id
//     if (queryId.value) {
//         refetchAgreen()
//     }
// })
const isLoading = computed(() => {
    return isPendingAdd.value || isPendingEdit.value || isPendingSign.value || isPendingAudit.value
})
function back() {
    console.log(signPath)
    router.go(-1)
    // router.push(signPath)
}

const config: IProps = {
    //
    accept: '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.wps,.jpg,.jpeg,.png', // pdf,.doc,.docx,.xlsx
    disabled: false,
    drag: false,
    fileSize: 50, // MB
    hidePlusIcon: false,
    isCheckWidthOrHeight: false,
    isPrivate: false,
    isVideo: false,
    limit: 10,
    listType: 'text',
    showRemoveIcon: true,
    splitSymbol: ',',
    tips: true,
}

// eslint-disable-next-line unused-imports/no-unused-vars
const extractedPath = fullPath.split('/').slice(0, -1).join('/')

async function addHandler() {
    instanceRef.value.validate((formResult) => {
        if (formResult) {
            addAgreen(form.value, {
                onSuccess: (result) => {
                    form.value.id = result
                    queryId.value = result
                    router.replace({
                        path,
                        query: {
                            id: result,
                        },
                    })
                    ElMessage.success('操作成功')
                },
            })
        }
    })
}

// 签章
function signAgreementHandler(file) {
    const data = {
        agreementId: form.value.id,
        fileId: file.id,
    }
    signAgreement(data, {
        onSuccess: (res) => {
            if (Number(res) === 1) {
                ElMessageBox.confirm('未授权电子签章', '提示', {
                    confirmButtonText: '去授权',
                    cancelButtonText: '取消',
                    type: 'warning',

                }).then(() => {
                    if (!unref(authUrlData)?.authUrl) {
                        return
                    }
                    window.open(unref(authUrlData)?.authUrl, '_self')
                })
                return
            }
            window.open(res)
        },
    })
}

// 签章过后提交
async function submitHandler(newStatus) {
    // const result = await formInstanceRef.value.formInstance
    //     .handleSubmit()
    instanceRef.value.validate((result) => {
        if (result) {
            const formData = cloneDeep(form.value)
            formData.status = newStatus
            editAgreen(formData, {
                onSuccess: (res) => {
                    if (Number(res) === 1) {
                        ElMessageBox.confirm('未授权电子签章', '提示', {
                            confirmButtonText: '去授权',
                            cancelButtonText: '取消',
                            type: 'warning',

                        }).then(() => {
                            if (!unref(authUrlData)?.authUrl) {
                                return
                            }
                            window.open(unref(authUrlData)?.authUrl, '_self')
                        })
                        return
                    }

                    form.value.status = newStatus
                    onSign.value = false
                    ElMessage.success('提交成功')
                },
            })
        }
    })
}
function audioHandler() {
    const status = auditStatusEnum.yes.value
    const formData = {
        id: form.value.id,
        status,
    }
    auditAgreement(formData, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            onSign.value = false
            refetchAgreen()
        },
    })
}
async function rejectHandler() {
    const formData = cloneDeep(rejectForm.value)
    formData.id = form.value.id
    auditAgreement(formData, {
        onSuccess: () => {
            closeRejectDialog()
            ElMessage.success('操作成功')
            onSign.value = false
            refetchAgreen()
        },
    })
}
function saveDrafHandler() {
    if (showAddSubmit.value) {
        addHandler()
    }
    else {
        editAgreen(form.value, {
            onSuccess: () => {
                ElMessage.success('保存成功')
            },
        })
    }
}
async function toSignHandler() {
    if (uploadFile.value && uploadFile.value.hasUploading) {
        ElMessage.warning('请耐心等待上传完成')
        return
    }
    const result = await formInstanceRef.value.formInstance
        .handleSubmit()
    if (!result) {
        return false
    }
    if (showAddSubmit.value) {
        addAgreen(form.value, {
            onSuccess: (result) => {
                form.value.id = result
                queryId.value = result
                router.replace({
                    path,
                    query: {
                        id: result,
                    },
                })
                refetchAgreen()
                onSign.value = true
                ElMessage.success('操作成功')
            },
        })
    }
    else {
        editAgreen(form.value, {
            onSuccess: () => {
                refetchAgreen()
                onSign.value = true
            },
        })
    }
}

const showReject = computed(() => {
    return (isPurchaser.value && form.value.status === agreementStatusEnum.pendingPartyA.value)
        || (isSupplier.value && form.value.status === agreementStatusEnum.pendingPartyB.value)
})

const disabledFile = computed(() => {
    return (isPurchaser.value && !([agreementStatusEnum.draft.value, agreementStatusEnum.pendingPartyA.value].includes(form.value.status)))
        || (isSupplier.value && form.value.status !== agreementStatusEnum.pendingPartyB.value) || onSign.value || isAdmin.value
})

const uploadFile = ref(null)

function uploadSuc() {
    formInstanceRef.value.formInstance.formInstance.validateField('contractFileList')
}
</script>

<template>
    <div>
        <div class="mb-20px flex justify-between">
            <ElButton type="primary"
                      @click="back"
            >
                返回
            </ElButton>

            <el-tag type="primary"
                    class="ml-10"
            >
                {{ agreementEnum.getLabel(form?.status) }}
            </el-tag>
        </div>

        <SearchForm ref="formInstanceRef"
                    v-model="form"
                    :group="group"
                    :rules="rules"
                    :loading="isLoading"
        >
            <template #group-header="{ title }">
                <div class="custom-group-header">
                    <span>
                        {{ title }} <span v-if="title === '协议文件'"
                                          class="text-size-5xl"
                        >提示：请审核协议文件并盖电子印章</span>
                    </span>
                </div>
            </template>

            <template #plus-field-contractFileList>
                <FlUploadProgress v-bind="config"
                                  :key="uploadKey"
                                  ref="uploadFile"
                                  v-model="form.contractFileList"
                                  :disabled="disabledFile"
                                  @success="uploadSuc"
                >
                    <template v-if="!isAdmin "
                              #operate="{ file }"
                    >
                        <template v-if="(file.unEsign) === SignStatusEnum.yes.value">
                            <el-tag type="primary"
                                    class="ml-10"
                            >
                                {{ isPurchaser ? '甲方' : isSupplier ? '乙方' : '' }}已签章
                            </el-tag>

                            <el-button type="primary"
                                       class="ml-10"
                                       :loading="isPendingSign"
                                       size="small"
                                       @click="() => {
                                           signAgreementHandler(file)

                                       }"
                            >
                                预览签章文件
                            </el-button>
                        </template>

                        <template v-if="onSign">
                            <el-button v-if="(file.unEsign) !== SignStatusEnum.yes.value"
                                       type="primary"
                                       class="ml-10"
                                       :loading="isPendingSign"
                                       size="small"
                                       @click="() => {
                                           signAgreementHandler(file)

                                       }"
                            >
                                在线签章
                            </el-button>
                        </template>
                    </template>
                </FlUploadProgress>
            </template>

            <template #plus-field-partyAResult>
                <span :style="{ color: form.status === agreementStatusEnum.rejectedByPartyA.value ? '#ec3535' : '#3d9dea' }">
                    {{ form.status === agreementStatusEnum.rejectedByPartyA.value ? '驳回' : '通过' }}
                </span>
            </template>

            <template #plus-field-partyBResult>
                <span :style="{ color: form.status === agreementStatusEnum.rejectedByPartyB.value ? '#ec3535' : '#3d9dea' }">
                    {{ form.status === agreementStatusEnum.rejectedByPartyB.value ? '驳回' : '通过' }}
                </span>
            </template>

            <template #plus-field-rejectFileListA>
                <FlUploadProgress v-bind="config"
                                  v-model="form.rejectFileList"
                                  disabled
                />
            </template>

            <template #plus-field-rejectFileListB>
                <FlUploadProgress v-bind="config"
                                  v-model="form.rejectFileList"
                                  disabled
                />
            </template>

            <template #footer>
                <div style="margin: 0 auto">
                    <template v-if="isPurchaser">
                        <!-- <el-button v-if="showAddSubmit"
                                   :loading="isLoading"
                                   type="primary"
                                   @click="addHandler"
                        >
                            提交
                        </el-button> -->

                        <template v-if="form.flag === FlagStatusEnum.yes.value">
                            <template v-if="form.status === agreementStatusEnum.draft.value">
                                <el-button v-if="onSign"
                                           @click="onSign = false"
                                >
                                    取消
                                </el-button>

                                <template v-if="!onSign && form.status === agreementStatusEnum.draft.value">
                                    <el-button @click="back">
                                        取消
                                    </el-button>

                                    <el-button :loading="isPendingEdit || isPendingAdd"
                                               @click="saveDrafHandler"
                                    >
                                        保存
                                    </el-button>

                                    <el-button :loading="isPendingEdit || isPendingAdd"
                                               type="primary"
                                               @click="toSignHandler"
                                    >
                                        去签章
                                    </el-button>
                                </template>

                                <!-- 草稿状态签约后提交 -->
                                <el-button v-if="onSign && form.status === agreementStatusEnum.draft.value"
                                           :loading="isPendingEdit"
                                           type="primary"
                                           @click="submitHandler(agreementStatusEnum.pendingPartyB.value)"
                                >
                                    提交
                                </el-button>
                            </template>

                            <template v-if="form.status === agreementStatusEnum.pendingPartyA.value">
                                <el-button v-if="onSign && form.status === agreementStatusEnum.pendingPartyA.value"
                                           :loading="isPendingAudit"
                                           type="primary"
                                           @click="audioHandler"
                                >
                                    确认签约
                                </el-button>

                                <el-button v-if="showReject"
                                           type="danger"
                                           @click="openRejectDialog"
                                >
                                    驳回
                                </el-button>
                            </template>
                        </template>
                    </template>

                    <template v-if="isSupplier">
                        <el-button v-if="onSign && form.status === agreementStatusEnum.pendingPartyB.value"
                                   :loading="isPendingAudit"
                                   type="primary"
                                   @click="audioHandler"
                        >
                            确认签约
                        </el-button>

                        <el-button v-if="showReject"
                                   type="danger"
                                   @click="openRejectDialog"
                        >
                            驳回
                        </el-button>
                    </template>
                </div>
            </template>
        </SearchForm>

        <PlusDialogForm ref="rejectFormRef"
                        v-model:visible="rejectVisible"
                        v-model="rejectForm"
                        :form="{ columns: rejectSchema,
                                 rules: rejectRules,
                        }"
                        :dialog="{
                            title: '驳回',
                        }"
                        @confirm="rejectHandler"
                        @cancel="closeRejectDialog"
        >
            <template #plus-field-files>
                <FlUploadProgress v-bind="config"
                                  ref="uploadRejectFile"
                                  v-model="rejectForm.files"
                />
            </template>
        </PlusDialogForm>
    </div>
</template>

<style scoped>

</style>
